<template>
  <!-- 封装轮播图 -->
  <div class="carousel">
    <!-- banner切换轮播图  从左往右切换  自动切换 手动拖拽  -->
    <div class="banner">
      <div class="banner-content" ref="bannerContent">
        <div
          v-for="(banner, index) in displayedbannersList"
          :key="index"
          class="banner-item"
        >
          <CustomImage :src="banner.img" alt="" />
        </div>
      </div>
      <!-- 点 -->
      <!-- banner-dots 修改为 -->
      <div class="banner-dots">
        <div
          v-for="n in bannersList.length"
          :key="n"
          class="banner-dot"
          :class="{ active: currentRealIndex === n - 1 }"
          @click="goToRealIndex(n - 1)"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import CustomImage from '@/components/common/Image/index.vue';
export default {
  components: {
    CustomImage,
  },
  props: {
    // 接收外部传入的轮播图数组
    bannersList: {
      type: Array,
      required: true,
      validator(value) {
        // 确保每个项都有 img 字段
        return value.every(item => item.img);
      },
    },
  },
  data() {
    return {
      totalbannersList: 0,
      startX: 0,
      currentX: 0,
      isDragging: false,
      autoPlayInterval: null,
      realBannerCount: 0, // 真实数量
      currentIndexBanner: 1, // 初始指向第一个真实项（克隆后是索引1）
      isAnimating: false, // 防止快速点击
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.updateBannerPosition(true);
      this.startAutoPlay();
    });

    this.realBannerCount = this.bannersList.length;
    const content = this.$refs.bannerContent;

    // 绑定事件
    content.addEventListener('mousedown', this.onDragStart);
    content.addEventListener('touchstart', this.onDragStart, {
      passive: false,
    });
    document.addEventListener('mousemove', this.onDragMove);
    document.addEventListener('touchmove', this.onDragMove, { passive: false });
    document.addEventListener('mouseup', this.onDragEnd);
    document.addEventListener('touchend', this.onDragEnd);

    // ✅ 添加 transitionend 监听
    content.addEventListener('transitionend', this.handleTransitionEnd);
  },
  computed: {
    displayedbannersList() {
      // ✅ 先判断 bannersList 是否有效
      if (!this.bannersList || this.bannersList.length === 0) {
        return []; // 返回空数组，避免后续操作
      }

      // ✅ 只有在 bannersList 有效时才取值
      const first = this.bannersList[0];
      const last = this.bannersList[this.bannersList.length - 1];

      // 返回：[克隆最后一张, 原始列表..., 克隆第一张]
      return [last, ...this.bannersList, first];
    },
    // 返回当前显示的是第几个真实页面（用于指示器）
    currentRealIndex() {
      if (this.currentIndexBanner === 0) {
        return this.bannersList.length - 1; // 克隆的最后一张 → 显示为最后一张
      } else if (
        this.currentIndexBanner ===
        this.displayedbannersList.length - 1
      ) {
        return 0; // 克隆的第一张 → 显示为第一张
      } else {
        return this.currentIndexBanner - 1; // 中间真实项
      }
    },
  },
  beforeDestroy() {
    this.stopAutoPlay();
    const content = this.$refs.bannerContent;
    content.removeEventListener('transitionend', this.handleTransitionEnd);

    content.removeEventListener('mousedown', this.onDragStart);
    content.removeEventListener('touchstart', this.onDragStart);
    document.removeEventListener('mousemove', this.onDragMove);
    document.removeEventListener('touchmove', this.onDragMove);
    document.removeEventListener('mouseup', this.onDragEnd);
    document.removeEventListener('touchend', this.onDragEnd);
  },
  methods: {
    handleTransitionEnd(e) {
      // 确保是 transform 动画结束
      if (e.propertyName !== 'transform') return;

      const total = this.displayedbannersList.length;

      // 当前显示的是克隆的第一张（最后一项），即索引 = total - 1
      if (this.currentIndexBanner === total - 1) {
        // ✅ 立即无动画跳回真实第一张（索引1）
        this.currentIndexBanner = 1;
        this.updateBannerPosition(true); // true = 无动画
      }
      // 可选：处理从克隆的最后一张（索引0）跳回真实最后一张
      else if (this.currentIndexBanner === 0) {
        this.currentIndexBanner = total - 2;
        this.updateBannerPosition(true);
      }
    },
    switchToIndex(newIndex, immediate = false) {
      this.currentIndexBanner = newIndex;
      this.updateBannerPosition(immediate);
    },
    initUnderline() {
      this.$nextTick(() => {
        const firstTab = this.$refs.tabItems[0];
        // ✅ 获取组件内部的原生 DOM 元素
        const dom = firstTab.$el || firstTab;
        this.underlineWidth = dom.offsetWidth;
        this.underlineLeft = dom.offsetLeft;
      });
    },
    setUnderline(index) {
      this.currentIndex = index;
      this.$nextTick(() => {
        const tab = this.$refs.tabItems[index];
        const dom = tab.$el || tab; // 兼容普通元素
        this.underlineWidth = dom.offsetWidth;
        this.underlineLeft = dom.offsetLeft;
      });
    },
    // --- 轮播图方法 ---
    updateBannerPosition(immediate = false) {
      this.$nextTick(() => {
        const content = this.$refs.bannerContent;
        if (!content) return; // 如果元素未找到，则直接返回

        const offset = -this.currentIndexBanner * 100;
        if (immediate) {
          content.style.transition = 'none';
        } else {
          content.style.transition = 'transform 0.3s ease';
        }

        content.style.transform = `translateX(${offset}%)`;
      });
    },
    startAutoPlay() {
      this.stopAutoPlay();
      this.autoPlayInterval = setInterval(() => {
        this.currentIndexBanner++; // 4 → 5（克隆A）
        this.updateBannerPosition(); // 触发滑动动画
        // 跳转由 onTransitionEnd 处理
      }, 3000);
    },

    stopAutoPlay() {
      if (this.autoPlayInterval) {
        clearInterval(this.autoPlayInterval);
        this.autoPlayInterval = null;
      }
    },

    // 拖拽开始
    onDragStart(e) {
      // 对于触摸事件，我们已经在addEventListener中设置了passive: false
      // 所以可以安全地调用preventDefault
      if (e.type === 'touchstart' || e.type === 'mousedown') {
        this.isDragging = true;
        this.startX = e.pageX || (e.touches && e.touches[0].pageX) || 0;
        this.stopAutoPlay(); // ✅ 停止自动播放
        this.$refs.bannerContent.style.transition = 'none';
        // 添加拖拽样式类
        this.$refs.bannerContent.classList.add('dragging');

        // 阻止默认行为和事件冒泡
        if (e.preventDefault) e.preventDefault();
        if (e.stopPropagation) e.stopPropagation();
      }
    },

    // 拖拽中
    onDragMove(e) {
      if (!this.isDragging) return;

      // 阻止默认行为，防止页面滚动
      if (e.preventDefault) e.preventDefault();

      const moveX = e.pageX || (e.touches && e.touches[0].pageX) || 0;
      this.currentX = moveX - this.startX;
      const offset =
        -this.currentIndexBanner * 100 +
        (this.currentX / window.innerWidth) * 100;
      this.$refs.bannerContent.style.transform = `translateX(${offset}%)`;

      // 阻止事件冒泡
      if (e.stopPropagation) e.stopPropagation();
    },

    // 拖拽结束
    onDragEnd(e) {
      if (!this.isDragging) return;
      this.isDragging = false;

      // 移除拖拽样式类
      this.$refs.bannerContent.classList.remove('dragging');

      const threshold = window.innerWidth * 0.2;
      let targetIndex = this.currentIndexBanner;

      if (this.currentX > threshold) {
        targetIndex--; // 上一张
      } else if (this.currentX < -threshold) {
        targetIndex++; // 下一张
      }

      if (targetIndex !== this.currentIndexBanner) {
        this.currentIndexBanner = targetIndex;
        this.updateBannerPosition(); // 触发动画
        // 跳转由 handleTransitionEnd 处理
      } else {
        // 回弹
        this.updateBannerPosition();
      }

      this.currentX = 0;
      this.startAutoPlay();

      // 阻止事件冒泡
      if (e && e.stopPropagation) e.stopPropagation();
    },
    // dots 点击跳转到第 n 个真实页面
    goToRealIndex(index) {
      this.stopAutoPlay();

      // 转换为 displayedbannersList 的索引
      const targetIndex = index + 1; // 真实项在中间
      this.currentIndexBanner = targetIndex;
      this.updateBannerPosition();

      this.$nextTick(() => {
        this.startAutoPlay();
      });
    },
    onTransitionEnd(e) {
      // 只处理 transform 动画
      if (e.propertyName !== 'transform') return;

      const total = this.displayedbannersList.length; // 应该是 6（0~5）

      // 当前显示的是克隆的第一张（最后一项，索引5）
      if (this.currentIndexBanner === total - 1) {
        console.log('到达克隆第一张，准备跳回真实第一张');

        // ✅ 立即无动画跳转到索引1（真实第一张）
        this.currentIndexBanner = 1;
        this.$refs.bannerContent.style.transition = 'none'; // 禁用动画
        this.updateBannerPosition(true); // 强制更新位置

        // 下一帧恢复动画（避免影响下一次滑动）
        this.$nextTick(() => {
          this.$refs.bannerContent.style.transition = 'transform 0.3s ease';
        });
      }
    },

    // 点击 tabs 切换
    handleTabClick(index) {
      this.activeIndex = index;
      console.log('切换到:', this.tabsCard[index].label);
    },
  },
  watch: {
    bannersList: {
      handler() {
        // 图片列表变化后，重置轮播图位置
        this.$nextTick(() => {
          this.currentIndexBanner = 1;
          this.updateBannerPosition(true); // 无动画重置
          this.startAutoPlay();
        });
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.banner {
  height: 180px;
  overflow: hidden;
  position: relative;

  .banner-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    transition: transform 0.3s ease;
    user-select: none; // 禁止文本选中

    &.dragging {
      cursor: grabbing;
    }

    .banner-item {
      width: 100%;
      height: 100%;
      width: 100%;
      flex-shrink: 0;
      img {
        height: 100%;
        width: 400px;
        object-fit: cover;
      }
    }
  }

  // 点
  .banner-dots {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    gap: 5px;

    .banner-dot {
      width: 6px;
      height: 6px;
      background-color: rgba(255, 255, 255, 0.5);
      border-radius: 50%;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .banner-dot.active {
      width: 8px;
      height: 8px;
      background-color: #fff;
    }
  }
}
</style>
